package jp.co.baka.pachinko.controller.regist;

import java.util.Date;

import jp.co.baka.pachinko.costant.CounterNames;
import jp.co.baka.pachinko.meta.UserMstMeta;
import jp.co.baka.pachinko.model.CounterMst;
import jp.co.baka.pachinko.model.UserMst;
import jp.co.baka.pachinko.service.CounterService;
import jp.co.baka.pachinko.service.UserService;
import jp.co.baka.pachinko.util.LogicalErrors;
import jp.co.baka.pachinko.util.MyContrller;

import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;
import org.slim3.datastore.GlobalTransaction;

import com.google.appengine.api.datastore.Key;

/**
 * 登録確定
 *
 * uuidリクエストパラメータより登録を確定する
 *
 * @author takemura
 *
 */
public class RegistConfirmController extends MyContrller {

    @Override
    public Navigation run() throws Exception {


        String uuid = param("uuid");

        UserMstMeta u = UserMstMeta.get();

        UserMst user = Datastore.query(u).filter(u.uuid.equal(uuid)).asSingle();
        if(user==null){
            LogicalErrors.addErrMessage("無効なリクエストです");
            return forward("../common/error.jsp");
        }


        if(user.getRegistDate()!=null){
            LogicalErrors.addErrMessage("登録済みです");
            return forward("../common/error.jsp");
        }



        Key counterKey = CounterService.getCounterKey(CounterNames.USER_MST_USER_ID);

        //トランザクションスタート
        GlobalTransaction gtx = Datastore.beginGlobalTransaction();

        CounterMst counter = gtx.get(CounterMst.class,counterKey);
        counter.increment();

        user.setUserId(counter.getCountValue());
        user.setRegistDate(new Date());

        gtx.put(user);
        gtx.put(counter);


        gtx.commit();


        UserService.addSessionAndCookie(user,request,response);


        return forward("regist_complete.jsp");
    }
}
